<template>
  <div class="player" :style="{width:$store.getters.playerParams.width}">
    <div class="playCtrl">
      <button type="button" class="ctl-btn" @click="backToBegin">&lt;</button>
      <button type="button" class="ctl-btn" @click="playOrPause">{{ playLabel }}</button>
      <button type="button" class="ctl-btn" @click="forwardToEnd">&gt;</button>
    </div>

    <div class="timeLine" @mousedown.stop="lineMouseDown">
      <div ref="progressLine" class="progressLine">
        <div ref="selDot" class="dot" @mousedown.stop="dragDown">
          <div class="sel-time">{{ selTime_s }}<i /></div>
        </div>
      </div>
      <div class="start-end">
        <span>{{ startTime_s }}</span>
        <span>{{ endTime_s }}</span>
      </div>
    </div>

    <div class="speedCtrl">
      <span class="title">播放速度</span>
      <div class="speeds">
        <div class="speed" :class="{active:speed === 0.5}" @click="changeSpeed(0.5)">0.5s</div>
        <div class="speed" :class="{active:speed === 1.0}" @click="changeSpeed(1.0)">1.0s</div>
        <div class="speed" :class="{active:speed === 1.5}" @click="changeSpeed(1.5)">1.5s</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
    name: 'Player',
    data() {
        return {
            selTime_s: '',
            startTime_s: '',
            endTime_s: '',
            isPlaying: false,
            speed: 1,
            currindex: 0,
            tiemsToPercentArr: [],
            times: [],
            dragReal: true, // 是否支持拖拖拽实时响应
            dragIng: false
        }
    },
    computed: {
        playLabel() {
            if (this.isPlaying) {
                return '||'
            } else {
                return '►'
            }
        }
    },
    watch: {
        currindex: {
            handler: function(name) {
                this.currindexChange()
            }
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.initTimeline()
        })
    },
    methods: {
        currindexChange() {
            const percent = this.tiemsToPercentArr[this.currindex]
            this.setLineStyle(percent)
            this.selTime_s = this.$moment(this.times[this.currindex]).format('YY/MM/DD HH:mm')
            this.$store.dispatch('playerTime', this.times[this.currindex])
            if (this.dragReal) {
                this.$store.dispatch('playerIndex', this.currindex)
            } else {
                if (!this.dragIng) {
                    this.$store.dispatch('playerIndex', this.currindex)
                }
            }
        },
        // 对应时间的百分比
        initPercentArr() {
            const length = this.times.length
            const percentArr = []
            for (var i = 0; i < length; i++) {
                percentArr.push(i / (length - 1))
            }
            this.tiemsToPercentArr = percentArr
        },
        initTimeline() {
            this.times = this.$store.getters.playerParams.times
            this.dragReal = this.$store.getters.playerParams.dragReal
            this.initPercentArr()
            this.currindex = 0
            this.startTime_s = this.$moment(this.times[0]).format('YY/MM/DD HH:mm')
            this.endTime_s = this.$moment(this.times[this.times.length - 1]).format('YY/MM/DD HH:mm')
            this.isPlaying = false
            if (this.timerPlay) {
                clearInterval(this.timerPlay)
            }
            this.$nextTick(() => {
                this.currindexChange()
            })
        },

        // 寻找最近的百分比，按传入时间计算跳跃式百分比
        findNearestPercent(percent) {
            const arr = this.tiemsToPercentArr
            let mid
            let l = 0
            let r = arr.length - 1
            // 保证指针最终停留在相邻的两个数,所以这里是判断是否大于1
            while (r - l > 1) {
                mid = Math.floor((l + r) / 2)
                // 如果目标数比中间小，所以范围在左边
                if (percent < arr[mid]) {
                    r = mid
                } else {
                    l = mid
                }
            }
            // 最后比较这两个数字的绝对差大小即可。
            if (Math.abs(percent - arr[l]) <= Math.abs(percent - arr[r])) {
                this.currindex = l
            } else {
                this.currindex = r
            }
        },
        // 点击时间轴---计算百分比
        lineMouseDown(e) {
            const progressLine = this.$refs.progressLine
            const percentNum = e.offsetX / (progressLine.offsetWidth * 1)
            this.findNearestPercent(percentNum)
        },
        // 时间轴推拽
        dragDown(e_dot_m) {
            const progressLineWidth = this.$refs.progressLine.offsetWidth * 1 // 进度条宽度
            const mouse_x_start = e_dot_m.clientX
            const dot_x_start = this.$refs.selDot.offsetLeft
            this.dragIng = true
            let percent
            document.onmousemove = (e_curr_m) => { // 鼠标按下并移动的事件
                // 点的起始位置 + 鼠标前后差
                var dot_x_new = dot_x_start + (e_curr_m.clientX - mouse_x_start)
                percent = dot_x_new / progressLineWidth
                // 移动当前元素
                if (percent >= 1) { // 不能拉越界
                    percent = 1
                } else if (percent <= 0) {
                    percent = 0
                }
                // console.log(left)
                this.findNearestPercent(percent)
            }
            document.onmouseup = (e) => {
                this.dragIng = false
                this.currindexChange()
                document.onmousemove = null
                document.onmouseup = null
            }
        },
        setLineStyle(percent) {
            this.$refs.selDot.style.left = percent * 100 + '%'
            this.$refs.progressLine.style.background = 'linear-gradient(to right, #1CDAFF, #1CDAFF ' + percent * 100 +
                    '%, #1a1b3e ' + percent * 100 + '%, #1a1b3e)'
        },
        changeSpeed(speed) {
            this.speed = speed
            this.play()
        },
        playOrPause() {
            this.isPlaying = !this.isPlaying
            this.play()
        },
        play() {
            if (this.isPlaying) {
                clearInterval(this.timerPlay)
                this.timerPlay = setInterval(() => {
                    this.currindex += 1
                    if (this.currindex >= this.tiemsToPercentArr.length) {
                        this.currindex = 0
                        this.isPlaying = false
                        clearInterval(this.timerPlay)
                    }
                }, this.speed * 1000)
            } else {
                clearInterval(this.timerPlay)
            }
        },
        backToBegin() {
            this.isPlaying = false
            clearInterval(this.timerPlay)
            this.currindex = 0
        },
        forwardToEnd() {
            this.isPlaying = false
            clearInterval(this.timerPlay)
            this.currindex = this.tiemsToPercentArr.length - 1
        }
    }
}
</script>

<style scoped lang="scss">
    $lineHeight: 10px;
    $dotSize: 14px;
    $background: rgba(14, 81, 133, 0.61);
    $border: #5f8db4;
    $height: #75b0fc;
    .player {
        position: absolute;
        bottom: 10px;
        left: 50%;
        width: 45%;
        height: 50px;
        transform: translateX(-50%);
        z-index: 11;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: $background;
        box-shadow: $height 0px 0px 8px inset;
        padding: 5px;

        .playCtrl {
            width: 120px;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: space-around;

            .ctl-btn {
                /*width: 50px;*/
                height: 40px;
                background: rgba(0, 0, 0, 0.0);
                border: none;
                color: white;
                font-size: 14px;
                font-weight: bold;
                cursor: pointer;

                &:hover {
                    background: rgba(0, 0, 0, 0.3);
                }
            }
        }

        .timeLine {
            width: calc(100% - 300px);
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: flex-end;
            padding: 0 10px;

            .progressLine {
                width: 100%;
                height: $lineHeight;
                background: $background;
                border-radius: 5px;
                box-sizing: border-box;
                position: relative;
                border: 1px solid $border;

                .dot {
                    position: absolute;
                    width: $dotSize;
                    height: $dotSize;
                    transform: translateX(-$dotSize*0.5);
                    top: -3px;
                    background: $height;
                    border: 2px solid $border;
                    box-sizing: border-box;
                    box-shadow: 0 0 10px 4px #faa30255;
                    border-radius: 50%;
                    cursor: pointer;
                    z-index: 5;

                    .sel-time {
                        position: absolute;
                        top: -30px;
                        border: 1px solid $border;
                        display: inline-block;
                        padding: 0 10px;
                        line-height: 15px;
                        border-radius: 13px;
                        white-space: nowrap;
                        transform: translateX(-50%);
                        color: #fff;
                        background: $background;
                        font-size: 11px;
                    }

                    i {
                        contain: size;
                        border: 1px solid $border;
                        background: $background;
                        width: 6px;
                        height: 6px;
                        display: block;
                        position: absolute;
                        transform: rotate(45deg);
                        bottom: -3px;
                        left: 50%;
                        border-top: 0;
                        border-left: 0;
                    }
                }
            }

            .start-end {
                display: flex;
                justify-content: space-between;
                align-items: center;

                span {
                    font-size: 11px;
                    line-height: 13px;
                    vertical-align: center;
                }
            }
        }

        .speedCtrl {
            width: 120px;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: space-around;
            flex-direction: column;

            .title {
                color: #fff;
                font-size: 11px;
            }

            .speeds {
                width: 100%;
                display: flex;
                justify-content: space-between;

                .speed {
                    font-size: 11px;
                    width: 33%;
                    height: 25px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    &.active{
                      box-shadow: $height 0px 0px 8px inset;
                    }

                }
            }
        }
    }

</style>
